﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using LibCommon;
using RTCCore;

namespace LibRTC.Core.MessageMap.ClientEvent {
    public class CleanupHandler : SimpleMessageHandler
    {
        private static ILogger LOGGER = LoggerFactory.GetLogger("CleanupHandler", null);

        private RTCCoreClient _coreClient;

        public CleanupHandler() {
            _rtcEvent = RTC_EVENT.RTCE_CLIENT;
            _name = "CleanupHandler";
        }

        public void SetRTCCoreClient(RTCCoreClient client) {
            Debug.Assert(null != client);
            _coreClient = client;
        }

        public override void Process(RTC_EVENT rtcEventType, object rtcEvent) {
            
            Debug.Assert(RTC_EVENT.RTCE_CLIENT == rtcEventType);
            Debug.Assert(rtcEvent is IRTCClientEvent);
            Debug.Assert(null != _coreClient);

            IRTCClientEvent clientEvent = (IRTCClientEvent) rtcEvent;

            RTC_CLIENT_EVENT_TYPE eventType = clientEvent.EventType;

            if (eventType == RTC_CLIENT_EVENT_TYPE.RTCCET_ASYNC_CLEANUP_DONE)
            {
                LOGGER.LogDebug("RTC_CLIENT_EVENT_TYPE.RTCCET_ASYNC_CLEANUP_DONE");

                // The RTC client has finished preparing for shutdown.
                _coreClient.Profile = null;

                if (null != _coreClient.RTCClient)
                {
                    // Unadvise for events from the RTC client
                    _coreClient.RTCClient.IRTCEventNotification_Event_Event -= new IRTCEventNotification_EventEventHandler(_coreClient.OnRTCEvent);
                    _coreClient.RTCClient.Shutdown();
                    _coreClient.RTCClient = null;
                }
                _coreClient.IPresenceUI.CloseUI();
            }

        }
    }
}